/*
 * @Author       : 吴豪
 * @Date         : 2021-12-4 15:56:22
 * @FilePath     : \book-manage-front\src\pages\userManage\usersComponents\CreateUser.tsx
 * @Description  : 新增用户模态框
 */

import { checkPhoneExist, deleterEnclosure, saveUserInfo } from '@/services/user';
import { serverUrl } from '@/utils/utils';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ProFormText, ProFormUploadButton } from '@ant-design/pro-form';
import { message, Modal } from 'antd';
import React, { useRef, useState } from 'react';

type LayoutType = Parameters<typeof ProForm>[0]['layout'];

/**
 * 新增用户组件，将父级传来的数据解构，并实现新增用户功能
 * @param props
 * @returns
 */
const CreateUser = (props: { isModalVisible?: any; isShowModal?: any; actionRef: any }) => {
  const { isModalVisible } = props;
  const { isShowModal } = props;
  const { actionRef } = props;
  const [formLayoutType] = useState<LayoutType>('horizontal');
  const [flag, setFlag] = useState<boolean>(false);
  const [enclosureId, setEnclosureId] = useState<string>();
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };

  const formRef = useRef<
    ProFormInstance<{
      aid: number;
      name: string;
      phone: string;
      password: string;
    }>
  >();

  /**
   * 新增用户
   */
  const handleOk = async () => {
    const data = await formRef.current?.validateFields();
    const param = {
      aid: -1,
      name: data?.name || '',
      phone: data?.phone || '',
      password: data?.password || '',
      enclosureId,
    };
    const response = await saveUserInfo(param);
    if (response.status === undefined) {
      message.success('添加成功！');
      isShowModal(false);
      actionRef.current.reload();
    } else {
      message.error('添加失败！');
    }
  };

  return (
    <Modal
      destroyOnClose
      title={'新增用户'}
      width="649px"
      visible={isModalVisible}
      onOk={handleOk}
      okButtonProps={{ disabled: flag }}
      onCancel={async () => {
        if (flag) {
          setFlag(false);
        }
        isShowModal(false);

        /**
         * 用户点击取消按钮时，删除已经上传的附件
         */
        if (enclosureId) {
          const parms = {
            enclosureId,
            aid: -1,
          };
          await deleterEnclosure(parms);
          setEnclosureId(undefined);
        }
      }}
    >
      <ProForm
        formRef={formRef}
        submitter={{
          submitButtonProps: {
            style: {
              display: 'none',
            },
          },
          resetButtonProps: {
            style: {
              display: 'none',
            },
          },
        }}
        {...layout}
        layout={formLayoutType}
        params={{}}
      >
        <ProFormText
          name="name"
          label="姓名"
          placeholder="请输入"
          rules={[
            {
              required: true,
              message: '请输入姓名',
            },
          ]}
        />
        <ProFormText
          name="phone"
          label="手机号码"
          placeholder="请输入"
          fieldProps={{
            //验证手机号的唯一性
            onBlur: async (event) => {
              const phone = event.target.value;
              if (phone) {
                const params = {
                  aid: -1,
                  phone,
                };
                const response = await checkPhoneExist(params);
                if (response.isExist) {
                  formRef.current?.setFieldsValue(response.userInfo!);
                  message.error('该手机号已存在！');
                  setFlag(true);
                } else {
                  setFlag(false);
                }
              }
            },
          }}
          rules={[
            {
              required: true,
              message: '请输入手机号',
            },
            { pattern: new RegExp(/^1[3-9]\d{9}/g), message: '请输入11位正确的手机号' },
          ]}
        />
        <ProFormText.Password
          name="password"
          label="密码"
          placeholder="请输入"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
            {
              pattern: new RegExp(/^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}$/),
              message: '请输入6-20位字母+数字的密码，不能有空格！',
            },
          ]}
        />
        <ProFormUploadButton
          /**
           * 上传附件
           */
          name="file"
          label="上传附件"
          title="upload"
          max={1}
          action={`${serverUrl()}/userManage/uploadEnclosure`}
          fieldProps={{
            headers: {
              token: localStorage.getItem('token')!,
            },
            method: 'POST',
            onChange: (info) => {
              if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
              }
              if (info.file.status === 'done') {
                message.success(`${info.file.name} 上传成功！`);
                setEnclosureId(info.file.response.data.enclosureId);
              } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 上传失败！`);
              }
            },
            onRemove: async () => {
              const parms = {
                enclosureId: enclosureId!,
                aid: -1,
              };
              await deleterEnclosure(parms);
              setEnclosureId(undefined);
            },
          }}
        />
      </ProForm>
    </Modal>
  );
};

export default CreateUser;
